package com.ley.springboot.seed.business.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ley.springboot.seed.business.entity.User;
import com.ley.springboot.seed.business.service.UserService;
import com.ley.springboot.seed.utils.web.Result;
import com.ley.springboot.seed.utils.web.ResultEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author author
 * @since 2020-06-05
 */
@RestController
@RequestMapping("/business/user")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "1", name = "page") Integer pageIndex,
                       @RequestParam(defaultValue = "10", name = "limit") Integer pageSize,User user) {
        IPage<User> page = new Page<>(pageIndex, pageSize);
        page = userService.page(page, Wrappers.<User>lambdaQuery()
                .like(StringUtils.hasText(user.getUserName()),User::getUserName,user.getUserName())
                .orderByDesc(User::getCreateTime));
        return ResultEntity.success(page);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        boolean flag = userService.removeById(id);
        return ResultEntity.success(flag);
    }

    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        boolean flag = userService.save(user);
        return ResultEntity.success(flag);
    }


    @PostMapping("/edit")
    public Result edit(@RequestBody User user) {
        Long id = user.getId();
        if (Objects.isNull(id)) {
            return ResultEntity.error("参数错误");
        } else {
            return ResultEntity.success(userService.updateById(user));
        }
    }
}
